<!--
  - Copyright (C) 2018-2019
  - All rights reserved, Designed By www.joolun.com
  芋道源码：
  ① 移除暂时用不到的 websocket
  ② 代码优化，补充注释，提升阅读性
-->
<template>
  <div class="w_full">
    <!-- 消息列表 -->
    <div class="execution" v-for="item in messageList" :key="item.id">
      <div class="c_888999 f-14 flexcenter timebox">
        {{ parseTime(item.createTime) }}
      </div>
      <div
        class="avue-comment"
        :class="item.sendFrom === 1 ? 'avue-comment--reverse' : ''"
      >
        <div class="avatar-div">
          <img
            :src="item.sendFrom === 1 ? user.avatar : mp.avatar"
            class="avue-comment__avatar"
          />
        </div>
        <div class="avue-comment__main">
          <el-popover
            :placement="item.sendFrom === 1 ? 'left' : 'right'"
            trigger="hover"
            popper-class="messagepoper"
          >
            <div>
              <el-button-group class="msgbtngroup">
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="复制"
                  placement="top-start"
                >
                  <el-button
                    v-if="item.type === 'text'"
                    size="mini"
                    icon="el-icon-copy-document"
                    class="f-15"
                    @click="handleCopy(item)"
                  ></el-button>
                </el-tooltip>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="引用"
                  placement="top-start"
                >
                  <el-button size="mini" v-if="item.type === 'text'" @click="handleQuote(item)">
                    <svg-icon class-name="f-15" icon-class="iyy" />
                  </el-button>
                </el-tooltip>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="转发"
                  placement="top-start"
                >
                  <el-button size="mini" @click="handleTranfer(item)">
                    <svg-icon class-name="f-15" icon-class="izf" />
                  </el-button>
                </el-tooltip>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="多选"
                  placement="top-start"
                >
                  <el-button
                    size="mini"
                    icon="el-icon-position"
                    class="f-15"
                  ></el-button>
                </el-tooltip>
                <el-dropdown class="borderleft" @command="handleCommand($event,item)">
                  <el-button
                    size="mini"
                    icon="el-icon-plus"
                    class="f-15"
                  ></el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="a">添加到个人素材库</el-dropdown-item>
                    <el-dropdown-item command="b">添加到企业素材库</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-button-group>
            </div>
            <div class="avue-comment__body" slot="reference">
              <!-- 【事件】区域 -->
              <div v-if="item.type === 'event' && item.event === 'subscribe'">
                <el-tag type="success" size="mini">关注</el-tag>
              </div>
              <div
                v-else-if="
                  item.type === 'event' && item.event === 'unsubscribe'
                "
              >
                <el-tag type="danger" size="mini">取消关注</el-tag>
              </div>
              <div v-else-if="item.type === 'event' && item.event === 'CLICK'">
                <el-tag size="mini">点击菜单</el-tag>【{{ item.eventKey }}】
              </div>
              <div v-else-if="item.type === 'event' && item.event === 'VIEW'">
                <el-tag size="mini">点击菜单链接</el-tag>【{{ item.eventKey }}】
              </div>
              <div
                v-else-if="
                  item.type === 'event' && item.event === 'scancode_waitmsg'
                "
              >
                <el-tag size="mini">扫码结果</el-tag>【{{ item.eventKey }}】
              </div>
              <div
                v-else-if="
                  item.type === 'event' && item.event === 'scancode_push'
                "
              >
                <el-tag size="mini">扫码结果</el-tag>【{{ item.eventKey }}】
              </div>
              <div
                v-else-if="
                  item.type === 'event' && item.event === 'pic_sysphoto'
                "
              >
                <el-tag size="mini">系统拍照发图</el-tag>
              </div>
              <div
                v-else-if="
                  item.type === 'event' && item.event === 'pic_photo_or_album'
                "
              >
                <el-tag size="mini">拍照或者相册</el-tag>
              </div>
              <div
                v-else-if="item.type === 'event' && item.event === 'pic_weixin'"
              >
                <el-tag size="mini">微信相册</el-tag>
              </div>
              <div
                v-else-if="
                  item.type === 'event' && item.event === 'location_select'
                "
              >
                <el-tag size="mini">选择地理位置</el-tag>
              </div>
              <div v-else-if="item.type === 'event'">
                <el-tag type="danger" size="mini">未知事件类型</el-tag>
              </div>
              <!-- 【消息】区域 -->
              <div v-else-if="item.type === 'text'" class="f-15 msgbox">
                <!-- {{ item.content }} -->
                <div v-html="getContentHtml(item.content)"></div>
              </div>
              <div v-else-if="item.type === 'voice'">
                <wx-voice-player
                  :url="item.mediaUrl"
                  :content="item.recognition"
                />
              </div>
              <div v-else-if="item.type === 'image'">
                <a target="_blank" :href="item.url">
                  <img :src="item.url" style="width: 100px" />
                </a>
              </div>
              <div
                v-else-if="item.type === 'video' || item.type === 'shortvideo'"
                style="text-align: center"
              >
                <wx-video-player :url="item.mediaUrl" />
              </div>
              <div v-else-if="item.type === 'link'" class="avue-card__detail">
                <el-link
                  type="success"
                  :underline="false"
                  target="_blank"
                  :href="item.url"
                >
                  <div class="avue-card__title">
                    <i class="el-icon-link"></i>{{ item.title }}
                  </div>
                </el-link>
                <div class="avue-card__info" style="height: unset">
                  {{ item.description }}
                </div>
              </div>
              <!-- TODO 芋艿：待完善 -->
              <div v-else-if="item.type === 'location'">
                <wx-location
                  :label="item.label"
                  :location-y="item.locationY"
                  :location-x="item.locationX"
                />
              </div>
              <div v-else-if="item.type === 'news'" style="width: 300px">
                <!-- TODO 芋艿：待测试；详情页也存在类似的情况 -->
                <wx-news :articles="item.articles" />
              </div>
              <div v-else-if="item.type === 'music'">
                <wx-music
                  :title="item.title"
                  :description="item.description"
                  :thumb-media-url="item.thumbMediaUrl"
                  :music-url="item.musicUrl"
                  :hq-music-url="item.hqMusicUrl"
                />
              </div>
            </div>
          </el-popover>
        </div>
      </div>
    </div>
    <TransferbyMessage
      v-if="opentransfer"
      :visable="opentransfer"
      :messageItem="messageItem"
      @close="handleCloseTransfer"
    />
    <!-- 添加到素材库 -->
    <add-material
      v-if="openmaterial"
      :visable="openmaterial"
      :messageItem="messageItem"
      @close="handleCloseMaterial"
    />
  </div>
</template>

<script>
import AddMaterial from './AddMaterial.vue';
import { emoji } from "@/assets/icons/emoji.js";
//   import { getMessagePage, sendMessage } from '@/api/mp/message'
//   import WxVideoPlayer from '@/views/mp/components/wx-video-play/main.vue';
//   import WxVoicePlayer from '@/views/mp/components/wx-voice-play/main.vue';
//   import WxNews from '@/views/mp/components/wx-news/main.vue';
//   import WxLocation from '@/views/mp/components/wx-location/main.vue';
//   import WxMusic from '@/views/mp/components/wx-music/main.vue';
// import { getUser } from "@/api/mp/mpuser";
import TransferbyMessage from "./TransferbyMessage.vue";
export default {
  name: "wxMsg",
  //   components: {
  //     WxVideoPlayer,
  //     WxVoicePlayer,
  //     WxNews,
  //     WxLocation,
  //     WxMusic
  //   },
  props: {
    // userId: {
    //   type: Number,
    //   required: true,
    // },
  },
  data() {
    return {
      // nowStr: new Date().getTime(), // 当前的时间戳，用于每次消息加载后，回到原位置；具体见 :id="'msg-div' + nowStr" 处
      // loading: false, // 消息列表是否正在加载中
      // loadMore: true, // 是否可以加载更多
      // list: [
      //   {
      //     sendFrom: 1,
      //     type: "text",
      //     content: "消息内容",
      //     createTime: "2023-12-20:20:52:00",
      //   },
      //   {
      //     sendFrom: 2,
      //     type: "text",
      //     content: "消息内容2",
      //     createTime: "2023-12-20:20:52:00",
      //   },
      //   {
      //     sendFrom: 1,
      //     type: "image",
      //     url: "https://cdn-qyb-hz.wxb.com/u/5424982/qyb/20240104/4e4ce81831d71c426db091b88e3de470.jpg",
      //     createTime: "2023-12-20:20:52:00",
      //   },
      //   {
      //     sendFrom: 2,
      //     type: "image",
      //     url: "https://cdn-qyb-hz.wxb.com/u/5424982/qyb/20240104/4e4ce81831d71c426db091b88e3de470.jpg",
      //     createTime: "2023-12-20:20:52:00",
      //   },
      // ], // 消息列表
      // queryParams: {
      //   pageNo: 1, // 当前页数
      //   pageSize: 14, // 每页显示多少条
      //   accountId: undefined,
      // },
      user: {
        // 由于微信不再提供昵称，直接使用“用户”展示
        nickname: "用户",
        avatar: require("@/assets/images/profile.jpg"),
        accountId: 0, // 公众号账号编号
      },
      mp: {
        nickname: "公众号",
        avatar: require("@/assets/images/wechat.png"),
      },
      // ========= 消息发送 =========
      sendLoading: false, // 发送消息是否加载中
      objData: {
        // 微信发送消息
        type: "text",
      },
      messageItem: null,
      opentransfer: false,
      openmaterial:false,
      materialType:''
    };
  },
  props:{
    messageList: {
      type:Array,
      default:[]
    },
    // loadMore:{// 是否可以加载更多
    //   type:Boolean,
    //   default:true
    // },
    // loading:{
    //   type:Boolean,
    //   default:false
    // },
    // nowStr:{
    //   default:''
    // },
  },
  components: {
    TransferbyMessage,
    AddMaterial
  },
  created() {
    // 获得用户信息
    // getUser(this.userId).then(response => {
    //   this.user.nickname = response.data.nickname && response.data.nickname.length > 0 ?
    //       response.data.nickname : this.user.nickname;
    //   this.user.avatar = response.data.avatar && this.user.avatar.length > 0 ?
    //       response.data.avatar : this.user.avatar;
    //   this.user.accountId = response.data.accountId;
    //   // 设置公众号账号编号
    //   this.queryParams.accountId = response.data.accountId;
    //   this.objData.accountId = response.data.accountId;
    //   // 加载消息
    //   console.log(this.queryParams)
    //   this.refreshChange()
    // })
  },
  methods: {
    handleCopy(item) {
      this.copy(item.content);
    },

    handleTranfer(item) {
      this.messageItem = item;
      this.opentransfer = true;
    },

    handleCloseTransfer() {
      this.opentransfer = false;
    },

    handleCommand(type,item){
      console.log('type:', type, item)
      this.messageItem = item;
      this.materialType = type
      this.openmaterial = true;
    },

    handleCloseMaterial(){
      this.openmaterial = false;
    },

    getContentHtml(content){
      let msgreg = /[[\u4E00-\u9FA5\\s]]+/g;
      // let unicode = /\\u{[A-Za-z0-9]*}/;
      // let unicode = /^.$/u;
      // let content = this.messageProps.currentMessage.content;
      // console.log("unicode.test(content)：",unicode.test(content),content);
      if(msgreg.test(content)){
        emoji.map(emj=>{
          let img = '<img src="'+emj.icon+'" width="20" height="20" align="absmiddle"/>';
          var reg=new RegExp("\\"+emj.name,"g");
          content = content.replace(reg,img);
        })
        // 去掉后面换行
        content = content.replace(/[\r\n]$/g, "");
        return content.replace(/\n/g,'<br>');
      }
      content = content.replace(/[\r\n]$/g, "");
      return '<span>'+ content.replace(/\n/g,'<br>').replace(/(^\n*)|(\n*$)/g,"")+ '</span>'
    },

    handleQuote(item){
      let name = ''
      if(item.sendFrom == 1){
        name = this.user.nickname
      }else{
        name = this.mp.nickname
      }
      let message = '「' + name + '：' + item.content + '」'+ '\r\n' + '- - - - - - - - - - - - - - -' + '\r\n';
      this.$store.commit("chat/SET_CHATMSG", message);
    },

    sendMsg() {
      if (!this.objData) {
        return;
      }
      // 公众号限制：客服消息，公众号只允许发送一条
      if (this.objData.type === "news" && this.objData.articles.length > 1) {
        this.objData.articles = [this.objData.articles[0]];
        this.$message({
          showClose: true,
          message: "图文消息条数限制在 1 条以内，已默认发送第一条",
          type: "success",
        });
      }

      // 执行发送
      this.sendLoading = true;
      sendMessage(
        Object.assign(
          {
            userId: this.userId,
          },
          {
            ...this.objData,
          }
        )
      )
        .then((response) => {
          this.sendLoading = false;
          // 添加到消息列表，并滚动
          this.list = [...this.list, ...[response.data]];
          this.scrollToBottom();
          // 重置 objData 状态
          this.$refs["replySelect"].deleteObj(); // 重置，避免 tab 的数据未清理
        })
        .catch(() => {
          this.sendLoading = false;
        });
    },

    loadingMore() {
      this.$emit('loadingMore')
    },
    
    // /**
    //  * 刷新回调
    //  */
    // refreshChange() {
    //   this.getPage(this.queryParams);
    // },
    // /** 定位到消息底部 */
    // scrollToBottom: function () {
    //   this.$nextTick(() => {
    //     let div = document.getElementById("msg-div" + this.nowStr);
    //     div.scrollTop = div.scrollHeight;
    //   });
    // },
  },
};
</script>
<style lang="scss" scoped>
.avue-comment {
  padding: 10px 0;
  display: flex;
  align-items: flex-start;
  &--reverse {
    flex-direction: row-reverse;
    .avue-comment__main {
      justify-content: flex-end !important;
    }
    .msgbox {
      background: #a0e658 !important;
      border-color: #a0e658 !important;
    }
  }
  &__avatar {
    width: 40px;
    height: 40px;
    border-radius: 4px;
    border: 1px solid transparent;
    box-sizing: border-box;
    vertical-align: middle;
  }
  &__main {
    flex: 1;
    position: relative;
    border-radius: 2px;
    display: flex;
    justify-content: flex-start;
    // justify-content: flex-end;
  }
  &__body {
    .msgbox {
      background: #fff;
      max-width: 800px;
      min-height: 30px;
      padding: 6px 12px;
      font-size: 15px;
      word-break: break-all;
      color: #000;
      border: 1px solid #e9e9e9;
      border-radius: 5px;
      margin-top: 4px;
    }
    // padding: 6px 12px;
    // overflow: hidden;
    // border-radius: 4px;
    // background: #fff;
    // color: #333;
    // font-size: 14px;
  }
}
.timebox {
  padding: 10px 0;
}
// .msg-div {
//   height: 100%;
//   overflow: auto;
// }
.msg-send {
  padding: 10px;
}
.avatar-div {
  text-align: center;
  width: 80px;
}
.send-but {
  float: right;
  margin-top: 8px !important;
}
.msgbtngroup {
  .el-button {
    padding: 5px !important;
  }
}
.borderleft {
  border-left: 1px solid #dcdfe6;
}
</style>